{{define "cp_custom_commands_edit_cmd"}}
{{template "cp_head" .}}
<header class="page-header">
    <h2>Editing Custom Command #{{.CC.LocalID}}</h2>
</header>

{{template "cp_alerts" .}}

<style>
    .cc-editor {
      font-family: Consolas, monospace;
    }
    .cc-group-disabled {
      text-decoration: line-through;
      color: #d2322d !important;
    }
</style>

<!-- Nav -->
<div class="row">
    <div class="col">
        <!-- Nav tabs -->
        <div class="tabs">
            <ul class="nav nav-tabs">
                <li class="nav-item {{if and (not .CurrentCommandGroup)}}active{{end}}">
                    <a data-partial-load="true" class="nav-link show {{if not .CurrentCommandGroup}}active{{end}}"
                        href="/manage/{{.ActiveGuild.ID}}/customcommands/">Ungrouped</a>
                </li>
                {{$dot := .}}
                {{range .CommandGroups}}
                <li
                    class="nav-item {{if $dot.CurrentCommandGroup}}{{if eq $dot.CurrentCommandGroup.ID .ID}}active{{end}}{{end}}">
                    <a data-partial-load="true"
                        class="nav-link show {{if $dot.CurrentCommandGroup}}{{if eq $dot.CurrentCommandGroup.ID .ID}}active{{end}}{{end}} {{if .Disabled}}cc-group-disabled{{end}}"
                        href="/manage/{{$dot.ActiveGuild.ID}}/customcommands/groups/{{.ID}}">{{.Name}}</a>
                </li>
                {{end}}
                <li class="nav-item">
                    <form class="form-horizontal" method="post"
                        action="/manage/{{.ActiveGuild.ID}}/customcommands/creategroup" data-async-form>
                        <input type="text" class="hidden" name="Name" value="Unnamed group">
                        <input clasS="nav-link show" type="submit" value="+"></input>
                    </form>
                </li>
            </ul>
            <!-- Tab panes -->
            <div class="tab-content">
                <div class="tab-pane active">
                    {{$guild := .ActiveGuild.ID}}
                    {{$g := .ActiveGuild}}
                    {{$dot := .}}
                    <form class="form-horizontal" method="post"
                        action="/manage/{{$guild}}/customcommands/commands/{{.CC.LocalID}}/update" data-async-form>
                        <button type="submit" class="hidden"
                            formaction="/manage/{{$guild}}/customcommands/commands/{{.CC.LocalID}}/update"
                            data-async-form-alertsonly></button>

                        <h2 class="card-title">
                            #{{.CC.LocalID}} -
                            {{index .CCTriggerTypes .CC.TriggerType}}{{if and (ne .CC.TriggerType 5) (ne .CC.TriggerType 6)}}:
                            <span
                                class="cc-text-trigger-span">{{.CC.TextTrigger}}</span>{{else if ne .CC.TriggerType 6}}:
                            Every
                            {{call .GetCCInterval .CC}}
                            {{if eq (call .GetCCIntervalType .CC) 1}}hour(s){{else}}minute(s){{end}}{{end}}
                        </h2>
                        <input type="text" class="hidden form-control" name="id" value="{{.CC.LocalID}}">
                        <div class="row">
                            <!-- Trigger -->
                            <div class="col-lg-4">
                                <div class="row">
                                    <div class="col">
                                        <div class="form-group">
                                            <label>Trigger type</label>
                                            <select class="form-control" id="trigger-type-dropdown" name="type"
                                                onchange="triggerTypeChanged(this)">

                                                <option value="none" {{if eq .CC.TriggerType 10}}selected{{end}}>None
                                                </option>
                                                <option value="cmd" {{if eq .CC.TriggerType 0}} selected{{end}}>Command
                                                    (mention/cmd
                                                    prefix)</option>
                                                <option value="prefix" {{if eq .CC.TriggerType 1}} selected{{end}}>
                                                    Starts with</option>
                                                <option value="contains" {{if eq .CC.TriggerType 2}} selected{{end}}>
                                                    Contains</option>
                                                <option value="regex" {{if eq .CC.TriggerType 3}} selected{{end}}>Regex
                                                </option>
                                                <option value="exact" {{if eq .CC.TriggerType 4}} selected{{end}}>Exact
                                                    match</option>
                                                <option value="reaction" {{if eq .CC.TriggerType 6}} selected{{end}}>
                                                    Reaction</option>
                                                <option value="interval_hours"
                                                    {{if eq (call .GetCCIntervalType .CC) 1}}selected{{end}}>
                                                    Hourly interval
                                                </option>
                                                <option value="interval_minutes"
                                                    {{if eq (call .GetCCIntervalType .CC) 0}}selected{{end}}>
                                                    Minute interval
                                                </option>
                                                <option value="component" {{if eq .CC.TriggerType 7}} selected{{end}}>
                                                    Message Component</option>
                                                <option value="modal" {{if eq .CC.TriggerType 8}} selected{{end}}>
                                                    Modal Submission</option>
                                                <option value="cron" {{ if eq .CC.TriggerType 9}} selected{{end}}>
                                                    Crontab (Beta)</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col" id="trigger-help">
                                        <p id="trigger-desc-none" class="text-danger">
                                            No trigger: can only be triggered manually by other custom
                                            commands
                                        </p>
                                        <p id="trigger-desc-cmd">
                                            <b>Command Trigger</b>: Works the same way as normal commands by using the
                                            command
                                            prefix or bot mention followed by the trigger.<br />
                                        </p>
                                        <p id="trigger-desc-prefix">
                                            Any message that starts with the trigger will run the command.
                                        </p>
                                        <p id="trigger-desc-contains">
                                            Any message that contains the trigger will run the command.
                                        </p>
                                        <p id="trigger-desc-regex">
                                            Any message that matches the provided regex will trigger the command.
                                        </p>
                                        <p id="trigger-desc-exact">
                                            Any message that is equal to the trigger will run the command.
                                        </p>
                                        <p id="trigger-desc-reaction">
                                            The command will trigger on the specified reaction events.
                                        </p>
                                        <p id="trigger-desc-interval_hours">
                                            The command will run at a hourly interval, for example every 5 hours.
                                        </p>
                                        <p id="trigger-desc-interval_minutes">
                                            The command will run at a minute interval, for example every 10 minutes.
                                        </p>
                                        <p id="trigger-desc-component">
                                            The command will run when a component (a button or a select menu) whose
                                            custom ID matches the given regex is used. BETA FEATURE.
                                        </p>
                                        <p id="trigger-desc-modal">
                                            The command will run when a modal whose custom ID matches the given regex is submitted. BETA FEATURE.
                                        </p>
                                        <p id="trigger-desc-cron">
                                            The command will run on a crontab interval, for example <code>45 23 * * 6</code> (23:45 every Saturday).
                                        </p>
                                    </div>
                                </div>
                            </div>
                            <div id="cc-text-trigger-details" class="hidden col-lg-8">
                                <div class="row">
                                    <div class="col-lg-12">
                                        <div class="form-group">
                                            <label id="cc-message-trigger-label">Trigger (<span id="trigger-length">{{len .CC.TextTrigger}}</span>/1000)</label>
                                            <label id="cc-customid-trigger-label">Component Custom ID Regex (<span id="trigger-length">{{len .CC.TextTrigger}}</span>/1000)</label>
                                            <label id="cc-cron-trigger-label">Crontab (<span id="trigger-length">{{len .CC.TextTrigger}}</span>/1000)</label>
                                            <div class="input-group mb-2">
                                                <div id="command-trigger-prepended-prefix" class="input-group-prepend">
                                                    <div class="input-group-text">{{.CommandPrefix}}</div>
                                                </div>
                                                <input id="trigger" type="text" class="form-control" name="trigger" placeholder="{{if eq .CC.TriggerType 9}}45 23 * * 6{{else}}fun{{end}}"
                                                    value="{{.CC.TextTrigger}}">
                                            </div>
                                            <div class="row">
                                              <div id="cc-text-trigger-case-sensitivity-toggle" class="col-lg-6"> {{checkbox "case_sensitive" "case_sensitive" "Case Sensitive?" .CC.TextTriggerCaseSensitive}}</div>
                                              <div class="col-lg-6">
                                                <div id="cc-message-trigger-details">
                                                    {{$disabledClass := ""}}
                                                    {{if not .IsGuildPremium}}{{$disabledClass = "disabled"}}{{end}}
                                                    {{checkbox "trigger_on_edit" "trigger_on_edit" "Trigger on message edits too? (Premium Only!)" .CC.TriggerOnEdit $disabledClass}}
                                                </div>
                                              </div>
                                            </div>
                                          </div>
                                    </div>
                                </div>
                                <div id="cc-interaction-trigger-details" class="hidden col-lg-8">
                                    <div class="row">
                                        <label for="interaction-defer-radio-{{.CC.LocalID}}">
                                            Defer a response when triggered
                                        </label>
                                        <div id="interaction-defer-radio-{{.CC.LocalID}}" class="col-lg-12">
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="interaction_defer_mode"
                                                    id="interaction-defer-none-{{.CC.LocalID}}" value="0"
                                                    {{if eq .CC.InteractionDeferMode 0}}checked{{end}}>
                                                <label class="form-check-label" for="interaction-defer-none-{{.CC.LocalID}}">
                                                    None
                                                </label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="interaction_defer_mode"
                                                    id="interaction-defer-message-{{.CC.LocalID}}" value="1"
                                                    {{if eq .CC.InteractionDeferMode 1}}checked{{end}}>
                                                <label class="form-check-label" for="interaction-defer-message-{{.CC.LocalID}}">
                                                    Message Response
                                                </label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="interaction_defer_mode"
                                                    id="interaction-defer-ephemeral-{{.CC.LocalID}}" value="2"
                                                    {{if eq .CC.InteractionDeferMode 2}}checked{{end}}>
                                                <label class="form-check-label" for="interaction-defer-ephemeral-{{.CC.LocalID}}">
                                                    Ephemeral Message Response
                                                </label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="interaction_defer_mode"
                                                    id="interaction-defer-update-{{.CC.LocalID}}" value="3"
                                                    {{if eq .CC.InteractionDeferMode 3}}checked{{end}}>
                                                <label class="form-check-label" for="interaction-defer-update-{{.CC.LocalID}}">
                                                    Update Message Response
                                                </label>
                                            </div>
                                        </div>
                                        <p>Deferring a response becomes the original interaction response. Use <code>editResponse</code> to edit a deferred response.</p>
                                    </div>
                                </div>
                            </div>
                            <div id="cc-reaction-trigger-details" class="hidden col-lg-8">
                                <div class="row">
                                    <div class="col-lg-12">
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="reaction_trigger_mode"
                                                id="reaction-mode-both-{{.CC.LocalID}}" value="0"
                                                {{if eq .CC.ReactionTriggerMode 0}}checked{{end}}>
                                            <label class="form-check-label" for="reaction-mode-both-{{.CC.LocalID}}">
                                                Added + Removed reactions
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="reaction_trigger_mode"
                                                id="reaction-mode-added-{{.CC.LocalID}}" value="1"
                                                {{if eq .CC.ReactionTriggerMode 1}}checked{{end}}>
                                            <label class="form-check-label" for="reaction-mode-added-{{.CC.LocalID}}">
                                                Added reactions only
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="reaction_trigger_mode"
                                                id="reaction-mode-removed-{{.CC.LocalID}}" value="2"
                                                {{if eq .CC.ReactionTriggerMode 2}}checked{{end}}>
                                            <label class="form-check-label" for="reaction-mode-removed-{{.CC.LocalID}}">
                                                Removed reactions only
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="cc-time-trigger-details" class="hidden col-lg-8">
                                <div class="row">
                                    <div id="cc-interval-trigger-details" class="hidden col-lg-4">
                                        <div class="form-group">
                                            <label>Interval</label>
                                            <input type="number" min="0" class="form-control" name="time_trigger_interval"
                                                placeholder="" value="{{call $dot.GetCCInterval .CC}}">
                                        </div>
                                    </div>
                                    <div class="col-lg-8">
                                        <div class="form-group">
                                            <label>Channel</label>
                                            <select id="time-trigger-channel" name="context_channel" class="form-control">
                                                {{textChannelOptions $g.Channels .CC.ContextChannel true "None"}}
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mt-3">
                                        <div class="form-group col-lg-3">
                                            <label for="trigger">Excluding hours (UTC)</label><br>
                                            <select name="time_trigger_excluding_hours" class="multiselect form-control"
                                                multiple="multiple" data-plugin-multiselect>
                                                {{$selectedExclHours := .CC.TimeTriggerExcludingHours}}
                                                {{range seq 0 24}}<option value="{{.}}"
                                                    {{if in $selectedExclHours .}}selected{{end}}>{{.}}</option>
                                                {{end}}
                                            </select>
                                        </div>
                                        <div class="form-group col-lg-3">
                                            <label for="trigger">Excluding weekdays (UTC)</label><br>
                                            <select name="time_trigger_excluding_days" class="multiselect form-control"
                                                multiple="multiple" data-plugin-multiselect>
                                                <option value="1"
                                                    {{if in .CC.TimeTriggerExcludingDays 1}}selected{{end}}>
                                                    Monday</option>
                                                <option value="2"
                                                    {{if in .CC.TimeTriggerExcludingDays 2}}selected{{end}}>
                                                    Tuesday</option>
                                                <option value="3"
                                                    {{if in .CC.TimeTriggerExcludingDays 3}}selected{{end}}>
                                                    Wednesday</option>
                                                <option value="4"
                                                    {{if in .CC.TimeTriggerExcludingDays 4}}selected{{end}}>
                                                    Thursday</option>
                                                <option value="5"
                                                    {{if in .CC.TimeTriggerExcludingDays 5}}selected{{end}}>
                                                    Friday</option>
                                                <option value="6"
                                                    {{if in .CC.TimeTriggerExcludingDays 6}}selected{{end}}>
                                                    Saturday</option>
                                                <option value="0"
                                                    {{if in .CC.TimeTriggerExcludingDays 0}}selected{{end}}>
                                                    Sunday</option>
                                            </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-lg-4">
                                <div class="form-group">
                                    <label>Name (<span id="name-length">{{len .CC.Name.String}}</span>/100) </label>
                                    <input type="text" class="form-control" id="name" name="name" placeholder="Enter a name" value="{{if .CC.Name.Valid}}{{.CC.Name.String}}{{end}}">
                                    <p>An optional name that can be used to identify the command.</p>
                                </div>
                            </div>
                             <div class="col-lg-4">
                                <div class="form-group">
                                    <label> Command Enabled?</label>
                                    {{checkbox "is_enabled" "is_enabled" "Enables or Disables the command" (not .CC.Disabled) }}
                                </div>
                            </div>
                            <div class="col-lg-4">
                                <div class="form-group">
                                  <label> Allow Public Imports?</label>
                                    {{checkbox "public" "public" "Allow anyone to view and copy this command" .CC.Public}}
                                </div>
                            </div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-lg-12">
                                <div class="form-group">

                                    <label for="responses">Response (<span
                                            class="cc-length-counter">x</span>/{{.MaxCCLength}})</label>
                                    <span style="float: right">
                                      <input type="checkbox" class="toggle-code-mirror" checked="true" id="toggle-code-mirror">
                                      <label for="toggle-code-mirror">Show CodeMirror Editor</label>
                                    </span>
                                    <!-- Use .btn-add for simplicity and let the page loader adjust. -->
                                    {{range .CC.Responses}}
                                    <div id="cc-responses" class="entry input-group  input-group-sm">
                                        <textarea class="form-control response-text-area tab-textbox cc-editor" name="responses"
                                            placeholder="Command body here" rows="5"
                                            oninput="onCCChanged(this)">{{.}}</textarea>
                                        <span class="input-group-append">
                                            <button class="btn btn-success btn-add btn-circle" type="button">
                                                <i class="fas fa-plus"></i>
                                            </button>
                                        </span>
                                    </div>
                                    {{else}}
                                    <div id="cc-responses" class="entry input-group  input-group-sm">
                                        <textarea class="form-control response-text-area tab-textbox cc-editor" name="responses"
                                            placeholder="Command body here" rows="5"
                                            oninput="onCCChanged(this)"></textarea>
                                        <span class="input-group-append">
                                            <button class="btn btn-success btn-add btn-circle" type="button">
                                                <i class="fas fa-plus"></i>
                                            </button>
                                        </span>
                                    </div>

                                    {{end}}
                                    <a class="mb-1 mt-1 mr-1 modal-basic btn btn-info btn-sm"
                                        href="#cc-help-modal">Info</a>
                                    {{if .CC.Public}}
                                    <a class="mb-1 mt-1 mr-1 modal-basic btn btn-info btn-sm"
                                        href="#cc-share-modal">Share</a>
                                    {{end}}
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-6">
                                <div class="form-group">
                                    <label>Custom command group</label>
                                    {{$selectedGroup := .CC.GroupID.Int64}}
                                    <select Name="GroupID" class="form-control">
                                        <option {{if eq $selectedGroup 0}}selected{{end}} value="0">None
                                        </option>
                                        {{range $dot.CommandGroups}}<option value="{{.ID}}"
                                            {{if eq $selectedGroup .ID}}selected{{end}}>{{.Name}}</option>
                                        {{end}}
                                    </select>
                                </div>

                                <h4>Last error</h4>
                                <p>{{if .CC.LastError}}<b>{{formatTime .CC.LastErrorTime.Time.UTC}}</b> - <code>
                                    {{.CC.LastError}}</code>{{else}}None{{end}}</p>

                                <div class="row">
                                    <div class="col-auto">
                                        <h4>Run count</h4>
                                        <p><code>{{.CC.RunCount}}</code></p>
                                    </div>
                                  
                                    <div class="col-auto">
                                        <h4>Last run</h4>
                                        <p>{{if .CC.LastRun.Valid}}{{formatTime .CC.LastRun.Time.UTC}}{{else}}None{{end}}</p>
                                    </div>
                                    {{if (eq .CC.TriggerType 5 9)}}
                                    <div class="col-auto">
                                        <h4>Next scheduled run</h4>
                                        <p>{{if .CC.NextRun.Valid}}{{formatTime .CC.NextRun.Time.UTC}}{{else}}None{{end}}</p>
                                    </div>
                                    {{end}}
                                </div>

                                <h4>Output errors as command response</h4>
                                {{checkbox "show_errors" "show_errors" "" .CC.ShowErrors}}

                                <h4>Redirect errors to selected channel</h4>
                                <select class="form-control" name="redirect_errors_channel" data-requireperms-send>
                                    {{textChannelOptions $g.Channels .CC.RedirectErrorsChannel true "None"}}
                                </select>
                            </div>
                            <div id="cc-extra-settings" class="col-lg-6">
                                <h3>Channel/User role restrictions</h3>
                                <div class="radio">
                                    <label>
                                        <input id="require-role-mode" type="radio" name="require_roles" value="on"
                                            {{if .CC.RolesWhitelistMode}}checked{{end}}>
                                        Require at least one of the roles in the following lists
                                    </label>
                                </div>
                                <div class="radio">
                                    <label>
                                        <input id="ignore-role-mode" type="radio" name="require_roles" value=""
                                            {{if not .CC.RolesWhitelistMode}}checked{{end}}>
                                        Ignore the roles in the following list
                                    </label>
                                </div>
                                <select name="roles" class="multiselect form-control" multiple="multiple"
                                    id="command-roles" data-plugin-multiselect>
                                    {{roleOptionsMulti $g.Roles nil .CC.Roles}}
                                </select>

                                <hr>

                                <div class="radio">
                                    <label>
                                        <input id="require-channel-mode" type="radio" name="require_channels" value="on"
                                            {{if .CC.ChannelsWhitelistMode}}checked{{end}}>
                                        Only run in the following channels
                                    </label>
                                </div>
                                <div class="radio">
                                    <label>
                                        <input id="ignore-channel-mode" type="radio" name="require_channels" value=""
                                            {{if not .CC.ChannelsWhitelistMode}}checked{{end}}>
                                        Ignore the channels in the following list
                                    </label>
                                </div>
                                <select name="channels" class="multiselect form-control" multiple="multiple"
                                    id="command-channels" data-plugin-multiselect>
                                    {{textChannelOptionsMulti $g.Channels .CC.Channels}}
                                </select>
                            </div>
                        </div>

                        <div class="row mt-4">
                            <div class="col">
                                <button type="submit" class="btn btn-success btn-block"
                                    formaction="/manage/{{$guild}}/customcommands/commands/{{.CC.LocalID}}/update"
                                    data-async-form-alertsonly
                                    id = "save-custom-command"
                                >Save</button>
                            </div>
                            <div class="col">
                                <button type="submit" class="btn btn-danger btn-block"
                                    formaction="/manage/{{$guild}}/customcommands/commands/{{.CC.LocalID}}/delete">Delete</button>
                            </div>
                        </div>
                        <div class="row mt-4" id="interval-cc-run-now">
                            <div class="col">
                                <button type="submit" class="btn btn-secondary btn-block" title="This will trigger this custom command immediately"
                                    formaction="/manage/{{$guild}}/customcommands/commands/{{.CC.LocalID}}/update_and_run">Run now</button>
                            </div>
                        </div>
                        <p class="help-block">Tip: Alt + Shift + S also saves the custom command </p>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

{{if .CC.Public}}
<div id="cc-share-modal" class="modal-block modal-header-color modal-block-info mfp-hide">
  <section class="card">
      <header class="card-header">
          <h2 class="card-title">Copy Import Link</h2>
      </header>
      <div class="card-body">
          <div class="modal-wrapper">
              <div class="modal-text">
                  <p class="help-block">To share custom command #<code>{{.CC.LocalID}}</code>, and allow users to
                  import it, copy the link below.
                  </p>
                  <div class="row no-gutters">
                    <div class="col-md-9">
                      <input type="text" style="border-radius: 0% !important;" id="public-link" class="form-control" name="Public Link" value="{{.PublicLink}}" readonly>
                    </div>
                    <div class="col-md-3">
                      <button id="copy-link-button" style="border-radius: 0% !important;" class="btn btn-quaternary"><i class="fas fa-copy p-1"> </i>Copy</button>
                    </div>
                  </div>
                  <script>
                      document.getElementById("copy-link-button").addEventListener("click", function() {
                        let copyText = document.getElementById("public-link");
                        copyText.select();
                        copyText.setSelectionRange(0, 99999); // For mobile devices
                        navigator.clipboard.writeText(copyText.value);
                        copyText.setSelectionRange(0, 0);
                        this.textContent = "Copied!";
                        setTimeout(() => {
                          this.innerHTML =`<i class="fas fa-copy p-1"> </i>Copy`;
                        }, 2000);
                      }, false);
                  </script>
              </div>
          </div>
      </div>
      <footer class="card-footer">
          <div class="row">
              <div class="col-md-8">
                <p>Total Imports: <code>{{.CC.ImportCount}}</code></p>
              </div>
              <div class="col-md-4 text-right">
                  <button class="btn btn-info modal-dismiss">Close</button>
              </div>
          </div>
      </footer>
  </section>
</div>
{{end}}

<div id="cc-help-modal" class="modal-block modal-header-color modal-block-info mfp-hide">
    <section class="card">
        <header class="card-header">
            <h2 class="card-title">Custom Command Information</h2>
        </header>
        <div class="card-body">
            <div class="modal-wrapper">
                <div class="modal-text">
                    <p class="help-block">Available template data is {{template "template_helper_user"}} (and much
                        more)
                    </p>
                    <p class="help-block">Execute bot commands using
                        <code>{{`{{exec "command" "arg1" "arg2"}}`}}</code>, Example:
                        <code>{{"{{exec \"role\" \"yagpdb\"}}"}}</code> will be the same as the user typing
                        <code>(mention or prefix) role yagpdb</code></p>
                    <p class="help-block">Arguments are available in a string array: <code>.CmdArgs</code><br>
                        Access
                        single arguments by index using <code>{{"{{index .CmdArgs 0}}"}}</code><br>Get the number of
                        arguments using <code>{{"{{len .CmdArgs}}"}}</code><br>Loop over them with
                        <br><code>{{"{{range .CmdArgs}}{{.}}"}} <- that dot will be replaced by the current argument we're looping over{{"{{end}}"}}</code><br>"end"
                        marks the end of the for loop.</p>
                    <!-- {{/* .IgnoreMe */}} -->
                    <p>
                        See the <a href="https://help.yagpdb.xyz/docs/reference/templates/" target="_blank">templating</a> and <a
                            href="https://help.yagpdb.xyz/docs/custom-commands/" target="_blank">custom
                            command</a>
                        docs for more info and join the support server if you have further questions. Custom
                        commands
                        for yagpdb are rather complicated for the time being.</p>
                    <p class="help-block">
                        YAGPDB will pick one message at random from all configured responses.
                    </p>
                </div>
            </div>
        </div>
        <footer class="card-footer">
            <div class="row">
                <div class="col-md-12 text-right">
                    <button class="btn btn-info modal-dismiss">OK</button>
                </div>
            </div>
        </footer>
    </section>
</div>

<script src="/static/vendorr/tln/tln.min.js"></script>
<link rel="stylesheet" href="/static/vendorr/tln/tln.min.css">
<style>
    html.dark .input-group-prepend > .input-group-text {
        background: #191c21;
    }
</style>

<script type="text/javascript">
    // support Alt + Shift + S shortcut to save custom command 
    $(document).on('keydown', (e) => {
        const event = e.originalEvent;
        if (event.altKey && event.shiftKey && event.code === 'KeyS') {
            const saveButton = document.getElementById('save-custom-command');
            if (saveButton) {
                saveButton.click();
                return false;
            }
        } 
    });

    $(function () {
        triggerTypeChanged();
        updateCCLength();
        updateTriggerLength();
        updateNameLength();
        setCMCheckbox();
    });

    var intervalTriggerEls = ['#interval-cc-run-now', '#cc-time-trigger-details', '#cc-interval-trigger-details'];
    var textTriggerEls = ['#cc-text-trigger-details', '#cc-extra-settings', '#cc-text-trigger-case-sensitivity-toggle'];
    var messageTriggerEls = [...textTriggerEls, '#cc-message-trigger-label', '#cc-message-trigger-details'];
    var interactionTriggerEls = [...textTriggerEls, '#cc-customid-trigger-label', '#cc-interaction-trigger-details'];

    // html elements that should be shown for specific trigger types and hidden otherwise
    var triggerTypeEls = {
        modal: [...interactionTriggerEls, '#trigger-desc-modal'],
        component: [...interactionTriggerEls, '#trigger-desc-component'],
        interval_hours: [...intervalTriggerEls, '#trigger-desc-interval_hours'],
        interval_minutes: [...intervalTriggerEls, '#trigger-desc-interval_minutes'],
        reaction: ['#cc-reaction-trigger-details', '#cc-extra-settings', '#trigger-desc-reaction'],
        cmd: [...messageTriggerEls, '#command-trigger-prepended-prefix', '#trigger-desc-cmd'],
        prefix: [...messageTriggerEls, '#trigger-desc-prefix'],
        contains: [...messageTriggerEls, '#trigger-desc-contains'],
        regex: [...messageTriggerEls, '#trigger-desc-regex'],
        exact: [...messageTriggerEls, '#trigger-desc-exact'],
        cron: ['#cc-text-trigger-details', '#cc-cron-trigger-label', '#cc-time-trigger-details', '#trigger-desc-cron'],
        none: ['#trigger-desc-none'],
    };

    function setCMCheckbox() {
      if(localStorage.getItem('cm-editor') === 'false'){
        $("#toggle-code-mirror").prop( "checked", false );
      } else {
        $("#toggle-code-mirror").prop( "checked", true );
      }
    }

    function triggerTypeChanged() {
        const curTriggerType = $('#trigger-type-dropdown').val();

        const elsToHide = [];
        const elsToShow = [];
        for (const [t, els] of Object.entries(triggerTypeEls)) {
            if (t === curTriggerType) elsToShow.push(...els);
            else elsToHide.push(...els);
        }

        // Order of operations is important: if we first show elements
        // applicable to the current trigger type, then hide elements applicable
        // to other trigger types, we may end up momentarily showing a relevant
        // element then hiding it. To avoid this undesirable behavior, first
        // hide elements from other trigger types and only then show elements
        // for the current trigger type.
        for (const el of elsToHide) $(el).addClass('hidden');
        for (const el of elsToShow) $(el).removeClass('hidden');

        refreshWarnings();
    }

    // issue warnings for common configurations that are indicative of user
    // error (but are not hard errors, since can be intended)
    function refreshWarnings() {
        const allChecks = [checkNoEmptyRequiredRoles, checkNoEmptyRequiredChannels, checkMissingIntervalTriggerChannel];

        const triggerType = $('#trigger-type-dropdown').val();
        for (const c of allChecks) {
            if (c.applicableTriggerTypes.includes(triggerType)) {
                c.run();
            } else {
                c.removeWarning();
            }
        }
    }

    function addWarningIfNotExists(id, text) {
        if (!document.getElementById(id)) {
            addAlert('warning', text, id);
        }
    }

    // 'require roles' mode with no required roles
    var checkNoEmptyRequiredRoles = {
        applicableTriggerTypes: ['modal', 'component', 'reaction', 'cmd', 'prefix', 'contains', 'regex', 'exact'],
        warningId: 'require-no-roles-warning',
        run() {
            const isRequireMode = $('#require-role-mode').prop('checked');
            const commandRolesMenu = $('#command-roles');
            if (isRequireMode && commandRolesMenu.val().length === 0) {
                addWarningIfNotExists(this.warningId,
                    "Requiring no roles effectively disables your command, meaning it will never run."
                    + " If your command has no role restrictions, set the mode to 'ignore roles' instead.",
                );
            } else {
                this.removeWarning();
            }
        },
        removeWarning() {
            $(`#${this.warningId}`).remove();
        },
    };
    $('#require-role-mode').change(() => checkNoEmptyRequiredRoles.run());
    $('#ignore-role-mode').change(() => checkNoEmptyRequiredRoles.run());
    $('#command-roles').change(() => checkNoEmptyRequiredRoles.run());

    var checkNoEmptyRequiredChannels = {
        applicableTriggerTypes: ['modal', 'component', 'reaction', 'cmd', 'prefix', 'contains', 'regex', 'exact'],
        warningId: 'require-no-channels-warning',
        run() {
            const isRequireMode = $('#require-channel-mode').prop('checked');
            const commandChannelsMenu = $('#command-channels');
            if (isRequireMode && commandChannelsMenu.val().length === 0) {
                addWarningIfNotExists(this.warningId,
                    "Requiring no channels effectively disables your command, meaning it will never run."
                    + " If your command has no channel restrictions, set the mode to 'ignore channels' instead.",
                );
            } else {
                this.removeWarning();
            }
        },
        removeWarning() {
            $(`#${this.warningId}`).remove();
        },
    };
    $('#require-channel-mode').change(() => checkNoEmptyRequiredChannels.run());
    $('#ignore-channel-mode').change(() => checkNoEmptyRequiredChannels.run());
    $('#command-channels').change(() => checkNoEmptyRequiredChannels.run());

    var checkMissingIntervalTriggerChannel = {
        applicableTriggerTypes: ['interval_hours', 'interval_minutes', 'cron'],
        warningId: 'time-trigger-no-channel-warning',
        run() {
            const selectedChannel = $('#time-trigger-channel').val();
            if (!selectedChannel) {
                addWarningIfNotExists(this.warningId,
                    "Selecting no channel for an interval command effectively disables your command, meaning it will never run."
                    + " If your command does not need to run in a specific channel, select a arbitrary one from the list instead.",
                );
            } else {
                this.removeWarning();
            }
        },
        removeWarning() {
            $(`#${this.warningId}`).remove();
        },
    };

    $('#time-trigger-channel').change(() => checkMissingIntervalTriggerChannel.run());

    function updateTriggerLength() {
        const triggerLength = $('#trigger-length');
        const trigger = $('#trigger');
        if (triggerLength > 0 && trigger && trigger.val()) {
            triggerLength
                .text(trigger.val().length)
                .toggleClass('text-danger', trigger.val().length > 1000);
        }
    }
    $('#trigger').keyup(updateTriggerLength);
  
    function updateNameLength() {
        const nameLength = $('#name-length');
        const name = $('#name');
        if (nameLength && name && name.val()) {
            nameLength
                .text(name.val().length)
                .toggleClass('text-danger', name.val().length > 100);
        }
    }
    $('#name').keyup(updateNameLength);

    function updateCCLength() {
        const textAreas = document.querySelectorAll('#cc-responses > textarea');
        const totalLength = Array.from(textAreas).reduce((acc, el) => {
            let len = countCodePoints(el.value);
            // The data received on the backend contains "\r\n" while it is simply "\n" on the JS side.
            // Adjust for this discrepancy by double-counting newline characters.
            const newlines = el.value.match(/\n/g);
            if (newlines) len += newlines.length;

            return acc + len;
        }, 0);

        $('.cc-length-counter')
            .text(totalLength)
            .toggleClass('text-danger', totalLength > {{.MaxCCLength}});
    }

    function countCodePoints(str) {
        return [...str].length;
    }

    function onCCChanged(textArea) {
       updateCCLength();
    }
</script>

<link rel="stylesheet" href="/static/vendorr/codemirror/lib/codemirror.css">
<link rel="stylesheet" href="/static/vendorr/codemirror/theme/ayu-mirage.css">
<script src="/static/vendorr/codemirror/lib/codemirror.js"></script>
<script src="/static/vendorr/codemirror/addon/display/placeholder.js"></script>
<script src="/static/vendorr/codemirror/mode/go/go.js"></script>
<script src="/static/js/yagFuncs.js"></script>
<style>
    .CodeMirror {
        width: 100% !important;
        max-width: 95% !important;
        resize: vertical;
    }
</style>
<script type="text/javascript">

    function setupCodeMirrorEditor(textArea) {
        var isCMEditor = localStorage.getItem('cm-editor')
        if(isCMEditor === 'false') return
        const codeMirror = CodeMirror.fromTextArea(textArea, {
            lineNumbers: true,
            mode: 'text/x-go',
            theme: 'ayu-mirage',
            lineWrapping: true,
            placeholder: 'Command body here',
            viewportMargin: Infinity,
            electricChars: false,
            extraKeys: {
                'Ctrl-Space': 'autocomplete',
                'Alt-F': 'findPersistent',
            },
        });

        codeMirror.on('change', (cm) => {
            cm.save();
            onCCChanged(cm.getTextArea());
        });
    }

    function removeCodeMirrorEditor(editor){
        editor.CodeMirror.toTextArea();
    }

    var initialTextAreas = document.querySelectorAll('.cc-editor');
    initialTextAreas.forEach((textArea) => setupCodeMirrorEditor(textArea));

    $("#toggle-code-mirror").change( value => {
        if(value.target.checked){
            localStorage.setItem('cm-editor', 'true')
            var textAreas = document.querySelectorAll('.cc-editor');
            textAreas.forEach((textArea) => setupCodeMirrorEditor(textArea));
        } else {
            localStorage.setItem('cm-editor', 'false')
            document.querySelectorAll('.CodeMirror').forEach((editor) => {
                removeCodeMirrorEditor(editor)
            });
        }
    })

    $(document).off('click', '.btn-add').off('click', '.btn-remove');
    // we need to reinitialize the codemirror instance for each new textarea, the script below is the old implementation coming from the spongebob.js file
    $(document).on('click', '.btn-add', function (e) {
		e.preventDefault();
		var currentEntry = $(this).parent().parent(),
		newEntry = $(currentEntry.clone()).insertAfter(currentEntry);
        newEntry.find('.CodeMirror').remove();
		newEntry.find('input, textarea').val('');
        setupCodeMirrorEditor(newEntry.find('textarea')[0]);
		newEntry.parent()
            .find('.entry:not(:last-of-type) .btn-add')
		    .removeClass('btn-add').addClass('btn-remove')
			.removeClass('btn-success').addClass('btn-danger')
            .attr('noconfirm', 'true')
			.html('<i class="fas fa-minus"></i>');
	    }).on('click', '.btn-remove', 
        function (e) {
            e.preventDefault();
            if (!confirm('Are you sure you want to delete this response? You will not be able to recover any unsaved changes.')) {
                return false;
            }else{
                $(this).parents('.entry:first').remove();
            }
		    return true;
        });
</script>

{{template "cp_footer" .}}

{{end}}
